import React, { useState, useEffect } from 'react';
import { Settings, FileText, BarChart3, Save, Download, Trash2, Plus, X } from 'lucide-react';
import { PluginSettings, DeliveryRecord } from '@/types';
import { getSettings, saveSettings, getDeliveryRecords } from '@/utils/storage';
import { exportRecordsToCSV, filterRecordsByDateRange, filterRecordsByStatus } from '@/utils/csv-export';

type TabType = 'settings' | 'records' | 'stats';

const OptionsApp: React.FC = () => {
  const [activeTab, setActiveTab] = useState<TabType>('settings');
  const [settings, setSettings] = useState<PluginSettings>({
    dailyLimit: 50,
    deliveryInterval: 3,
    autoScroll: true,
    blacklistCompanies: [],
    filterKeywords: [],
    deliveryMessage: '您好，我对这个职位很感兴趣，希望能有机会详细了解。'
  });
  
  const [records, setRecords] = useState<DeliveryRecord[]>([]);
  const [filteredRecords, setFilteredRecords] = useState<DeliveryRecord[]>([]);
  const [newCompany, setNewCompany] = useState('');
  const [newKeyword, setNewKeyword] = useState('');
  const [dateRange, setDateRange] = useState({ start: '', end: '' });
  const [statusFilter, setStatusFilter] = useState('all');
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    applyFilters();
  }, [records, dateRange, statusFilter]);

  const loadData = async () => {
    try {
      const [currentSettings, currentRecords] = await Promise.all([
        getSettings(),
        getDeliveryRecords()
      ]);
      
      setSettings(currentSettings);
      setRecords(currentRecords);
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  const applyFilters = () => {
    let filtered = [...records];
    
    // 按日期范围过滤
    if (dateRange.start && dateRange.end) {
      filtered = filterRecordsByDateRange(filtered, dateRange.start, dateRange.end);
    }
    
    // 按状态过滤
    filtered = filterRecordsByStatus(filtered, statusFilter);
    
    setFilteredRecords(filtered);
  };

  const handleSaveSettings = async () => {
    setIsSaving(true);
    try {
      await saveSettings(settings);
      alert('设置保存成功！');
    } catch (error) {
      console.error('保存设置失败:', error);
      alert('保存设置失败，请重试');
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddCompany = () => {
    if (newCompany.trim() && settings.blacklistCompanies.indexOf(newCompany.trim()) === -1) {
      setSettings({
        ...settings,
        blacklistCompanies: [...settings.blacklistCompanies, newCompany.trim()]
      });
      setNewCompany('');
    }
  };

  const handleRemoveCompany = (company: string) => {
    setSettings({
      ...settings,
      blacklistCompanies: settings.blacklistCompanies.filter(c => c !== company)
    });
  };

  const handleAddKeyword = () => {
    if (newKeyword.trim() && settings.filterKeywords.indexOf(newKeyword.trim()) === -1) {
      setSettings({
        ...settings,
        filterKeywords: [...settings.filterKeywords, newKeyword.trim()]
      });
      setNewKeyword('');
    }
  };

  const handleRemoveKeyword = (keyword: string) => {
    setSettings({
      ...settings,
      filterKeywords: settings.filterKeywords.filter(k => k !== keyword)
    });
  };

  const handleExportRecords = () => {
    const recordsToExport = filteredRecords.length > 0 ? filteredRecords : records;
    exportRecordsToCSV(recordsToExport);
  };

  const handleClearRecords = async () => {
    if (confirm('确定要清空所有投递记录吗？此操作不可恢复。')) {
      try {
        await chrome.storage.local.remove('boss_auto_delivery_records');
        setRecords([]);
        setFilteredRecords([]);
        alert('投递记录已清空');
      } catch (error) {
        console.error('清空记录失败:', error);
        alert('清空记录失败，请重试');
      }
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'success': return '投递成功';
      case 'failed': return '投递失败';
      case 'pending': return '投递中';
      default: return '未知状态';
    }
  };

  const getStatusBadgeClass = (status: string) => {
    switch (status) {
      case 'success': return 'status-badge status-success';
      case 'failed': return 'status-badge status-failed';
      case 'pending': return 'status-badge status-pending';
      default: return 'status-badge';
    }
  };

  const calculateStats = () => {
    const total = records.length;
    const success = records.filter(r => r.status === 'success').length;
    const failed = records.filter(r => r.status === 'failed').length;
    const pending = records.filter(r => r.status === 'pending').length;
    const successRate = total > 0 ? Math.round((success / total) * 100) : 0;
    
    return { total, success, failed, pending, successRate };
  };

  const stats = calculateStats();

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="settings-container">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Boss直聘自动投递助手</h1>
          <p className="text-gray-600">管理您的投递设置、查看投递记录和统计数据</p>
        </div>

        {/* 标签页导航 */}
        <div className="flex space-x-2 mb-8">
          <button
            onClick={() => setActiveTab('settings')}
            className={`tab-button ${activeTab === 'settings' ? 'active' : ''}`}
          >
            <Settings className="w-4 h-4 mr-2 inline" />
            基本设置
          </button>
          <button
            onClick={() => setActiveTab('records')}
            className={`tab-button ${activeTab === 'records' ? 'active' : ''}`}
          >
            <FileText className="w-4 h-4 mr-2 inline" />
            投递记录
          </button>
          <button
            onClick={() => setActiveTab('stats')}
            className={`tab-button ${activeTab === 'stats' ? 'active' : ''}`}
          >
            <BarChart3 className="w-4 h-4 mr-2 inline" />
            数据统计
          </button>
        </div>

        {/* 设置页面 */}
        {activeTab === 'settings' && (
          <div className="space-y-6">
            <div className="settings-card">
              <h2 className="text-xl font-semibold text-gray-900 mb-6">投递参数设置</h2>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="form-group">
                  <label className="form-label">单日投递上限</label>
                  <input
                    type="number"
                    min="1"
                    max="150"
                    value={settings.dailyLimit}
                    onChange={(e) => setSettings({
                      ...settings,
                      dailyLimit: Math.min(150, Math.max(1, parseInt(e.target.value) || 1))
                    })}
                    className="form-input"
                  />
                  <p className="text-xs text-gray-500 mt-1">每日最多投递职位数量，最大值为150</p>
                </div>

                <div className="form-group">
                  <label className="form-label">投递间隔时间（秒）</label>
                  <input
                    type="range"
                    min="1"
                    max="10"
                    value={settings.deliveryInterval}
                    onChange={(e) => setSettings({
                      ...settings,
                      deliveryInterval: parseInt(e.target.value)
                    })}
                    className="slider"
                  />
                  <div className="flex justify-between text-xs text-gray-500 mt-1">
                    <span>1秒</span>
                    <span>当前: {settings.deliveryInterval}秒</span>
                    <span>10秒</span>
                  </div>
                </div>
              </div>

              <div className="form-group">
                <label className="form-label flex items-center">
                  <span>自动滚动翻页</span>
                  <button
                    onClick={() => setSettings({
                      ...settings,
                      autoScroll: !settings.autoScroll
                    })}
                    className={`switch ml-4 ${settings.autoScroll ? 'enabled' : 'disabled'}`}
                  >
                    <span className="switch-thumb"></span>
                  </button>
                </label>
                <p className="text-xs text-gray-500 mt-1">自动检测页面底部并滚动加载更多职位</p>
              </div>

              <div className="form-group">
                <label className="form-label">投递消息模板</label>
                <textarea
                  value={settings.deliveryMessage}
                  onChange={(e) => setSettings({
                    ...settings,
                    deliveryMessage: e.target.value
                  })}
                  className="form-textarea"
                  rows={3}
                  placeholder="请输入投递时的消息模板..."
                />
              </div>
            </div>

            <div className="settings-card">
              <h2 className="text-xl font-semibold text-gray-900 mb-6">过滤规则设置</h2>
              
              <div className="form-group">
                <label className="form-label">黑名单公司</label>
                <div className="tag-input">
                  {settings.blacklistCompanies.map((company, index) => (
                    <span key={index} className="tag">
                      {company}
                      <X
                        className="w-3 h-3 tag-remove"
                        onClick={() => handleRemoveCompany(company)}
                      />
                    </span>
                  ))}
                  <input
                    type="text"
                    value={newCompany}
                    onChange={(e) => setNewCompany(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleAddCompany()}
                    placeholder="输入公司名称后按回车添加"
                    className="flex-1 min-w-[200px] outline-none bg-transparent"
                  />
                </div>
                <p className="text-xs text-gray-500 mt-1">包含这些关键词的公司将被跳过投递</p>
              </div>

              <div className="form-group">
                <label className="form-label">过滤关键词</label>
                <div className="tag-input">
                  {settings.filterKeywords.map((keyword, index) => (
                    <span key={index} className="tag">
                      {keyword}
                      <X
                        className="w-3 h-3 tag-remove"
                        onClick={() => handleRemoveKeyword(keyword)}
                      />
                    </span>
                  ))}
                  <input
                    type="text"
                    value={newKeyword}
                    onChange={(e) => setNewKeyword(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleAddKeyword()}
                    placeholder="输入关键词后按回车添加"
                    className="flex-1 min-w-[200px] outline-none bg-transparent"
                  />
                </div>
                <p className="text-xs text-gray-500 mt-1">包含这些关键词的职位将被跳过投递</p>
              </div>
            </div>

            <div className="flex justify-end">
              <button
                onClick={handleSaveSettings}
                disabled={isSaving}
                className="btn-primary flex items-center"
              >
                <Save className="w-4 h-4 mr-2" />
                {isSaving ? '保存中...' : '保存设置'}
              </button>
            </div>
          </div>
        )}

        {/* 投递记录页面 */}
        {activeTab === 'records' && (
          <div className="space-y-6">
            <div className="settings-card">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-xl font-semibold text-gray-900">投递记录</h2>
                <div className="flex space-x-2">
                  <button onClick={handleExportRecords} className="btn-secondary flex items-center">
                    <Download className="w-4 h-4 mr-2" />
                    导出CSV
                  </button>
                  <button onClick={handleClearRecords} className="btn-danger flex items-center">
                    <Trash2 className="w-4 h-4 mr-2" />
                    清空记录
                  </button>
                </div>
              </div>

              {/* 筛选工具栏 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div>
                  <label className="form-label">开始日期</label>
                  <input
                    type="date"
                    value={dateRange.start}
                    onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="form-label">结束日期</label>
                  <input
                    type="date"
                    value={dateRange.end}
                    onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="form-label">投递状态</label>
                  <select
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className="form-select"
                  >
                    <option value="all">全部状态</option>
                    <option value="success">投递成功</option>
                    <option value="failed">投递失败</option>
                    <option value="pending">投递中</option>
                  </select>
                </div>
              </div>

              {/* 记录表格 */}
              <div className="records-table">
                <div className="table-header">
                  <div className="grid grid-cols-7 gap-4 table-cell font-medium text-gray-700">
                    <div>投递时间</div>
                    <div>职位名称</div>
                    <div>公司名称</div>
                    <div>薪资范围</div>
                    <div>所在城市</div>
                    <div>投递状态</div>
                    <div>操作</div>
                  </div>
                </div>
                <div className="max-h-96 overflow-y-auto">
                  {filteredRecords.length > 0 ? (
                    filteredRecords.map((record, index) => (
                      <div key={index} className="table-row">
                        <div className="grid grid-cols-7 gap-4 table-cell">
                          <div className="text-gray-600">
                            {new Date(record.deliveryTime).toLocaleString('zh-CN')}
                          </div>
                          <div className="font-medium text-gray-900 truncate">
                            {record.jobTitle}
                          </div>
                          <div className="text-gray-600 truncate">
                            {record.companyName}
                          </div>
                          <div className="text-gray-600">
                            {record.salary}
                          </div>
                          <div className="text-gray-600">
                            {record.location}
                          </div>
                          <div>
                            <span className={getStatusBadgeClass(record.status)}>
                              {getStatusText(record.status)}
                            </span>
                          </div>
                          <div>
                            <a
                              href={record.detailUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-boss-green hover:text-primary-600 text-sm"
                            >
                              查看详情
                            </a>
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-8 text-gray-500">
                      {records.length === 0 ? '暂无投递记录' : '没有符合条件的记录'}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 数据统计页面 */}
        {activeTab === 'stats' && (
          <div className="space-y-6">
            <div className="stats-grid">
              <div className="stat-card">
                <div className="text-3xl font-bold text-boss-green mb-2">{stats.total}</div>
                <div className="text-sm text-gray-600">总投递数</div>
              </div>
              <div className="stat-card">
                <div className="text-3xl font-bold text-green-500 mb-2">{stats.success}</div>
                <div className="text-sm text-gray-600">投递成功</div>
              </div>
              <div className="stat-card">
                <div className="text-3xl font-bold text-red-500 mb-2">{stats.failed}</div>
                <div className="text-sm text-gray-600">投递失败</div>
              </div>
              <div className="stat-card">
                <div className="text-3xl font-bold text-boss-green mb-2">{stats.successRate}%</div>
                <div className="text-sm text-gray-600">成功率</div>
              </div>
            </div>

            <div className="settings-card">
              <h2 className="text-xl font-semibold text-gray-900 mb-6">投递趋势</h2>
              <div className="text-center py-12 text-gray-500">
                <BarChart3 className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                <p>图表功能开发中...</p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OptionsApp;